import React from "react";
import { BrowserRouter, Routes, Route, Navigate } from "react-router-dom";
import { RouterRowState } from "../types";
import { ROUTES_LIST } from "./routes";

interface PropsType extends RouterRowState {}

const BeforeEachRouter: React.FC<PropsType> = (props) => {
  const token = localStorage.getItem('token');
  // 登录验证 token
  if(props.authLogin && !token) return <Navigate to="/login"></Navigate>
  // 正常访问
  else return props.element;
};

const renderView = (routes: RouterRowState[]) => {
  return routes.map((v, i) => {
    return (
      <Route
        path={v.path}
        // 加载前置守卫组件
        element={<BeforeEachRouter {...v}></BeforeEachRouter>}
        key={i}
      >
        {/* 递归渲染子路由 */}
        {v.children && renderView(v.children)}
      </Route>
    );
  });
};

const Router: React.FC = () => {
  const routerView = renderView(ROUTES_LIST);
  return (
    <BrowserRouter>
      <React.Suspense fallback={<div>路由加载中...</div>}>
        <Routes>{routerView}</Routes>
      </React.Suspense>
    </BrowserRouter>
  );
};

export default Router;
